<?php

class ContentContextService extends FServiceBase
{    
    /**
    * Get all available contexts of a content type
    * 
    * @param string contentType
    * @param string contextType edit | search | view | list
    * @return FServiceModel
    */
    public function getContexts($params){
        $contentType = $this->getParam($params,'contentType','');
        if (empty($contentType))
            return $this->result->fail(ERROR_INVALID_DATA, 'Invalid content type.');
        
        $contextType = $this->getParam($params,'contextType','edit');
        $criteria = new CDbCriteria();
        $criteria->with = array('contentType');
        $criteria->compare('t.status',true);
        $criteria->compare('t.type',$contextType);
        $criteria->compare('"contentType".model',$contentType);
        $criteria->order = 'is_default DESC';
        
        $this->result->processed('contexts', ContentContext::model()->findAll($criteria));
    }
    
    /**
    * Get the DbCriteria object of a search context
    * 
    * @param int id ContentContext ID
    * @param array params search criteria parameter
    * @return FServiceModel
    */
    public function getSearchCriteria($params) {
        $searchContext = ContentContext::model()->findByPk($this->getParam($params,'id',0));
        if (!$searchContext)
            return $this->result->fail(ERROR_INVALID_DATA,Yii::t('Cms.ContentContext','Invalid ID.'));
        if ($searchContext->type != 'search')
            return $this->result->fail(ERROR_INVALID_DATA,Yii::t('Cms.ContentContext','Not a search context.'));
            
        $searchId = trim(reset(array_reverse(explode('.', $searchContext->route))), '_');
        $contentType = $searchContext->contentType;
        /**
        * @var CActiveRecord
        */
        $model = Yii::createComponent($contentType->model);
        $model->unsetAttributes();
        $model->setScenario($searchId);
        
        // clean the empty params because they are submitted with ''
        $criteriaParams = $this->getParam($params,'params',array());
        foreach($criteriaParams as $key=>$value)
            if ($value == '')
                unset($criteriaParams[$key]);
                
        $model->setAttributes($criteriaParams);
        
        $className = get_class($model);
        $rModel = new ReflectionClass($className);
        if ($rModel->hasMethod($searchId))
            $criteria = $model->$searchId()->getCriteria();
        else
            $criteria = $model->search()->getCriteria();
            
        $this->result->processed('criteria', $criteria);
        return $this->result;
    }
    
    
    /**
    * Get a ContentContext model given its ID
    * 
    * @param int id ContentContext ID
    * @return FServiceModel
    */
    public function get($params){
        $model = ContentContext::model()->findByPk($this->getParam($params, 'id',0));
        if (! $model)
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Cms.ContentContext','Invalid ID.'));
        $this->result->processed('model', $model);
        return $this->result;
    }
    
    public function save($params) {
        /**
        * @var CModel
        */
        $model = $this->getModel($params['ContentContext'],'ContentContext');
        $this->result->processed('model', $model);
        
        if (! $model->validate())
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Cms.ContentContext', 'Submitted data is missing or invalid.'));
        elseif ($this->getParam($params, 'validateOnly',0) == TRUE)
            return $this->result;
        elseif (! $model->save())
            $this->result->fail(ERROR_HANDLING_DB, Yii::t('Cms.ContentContext','Error while saving submitted data into database.'));
        
        return $this->result;
    }


    public function delete($params) {
        $ids = $this->getParam($params, 'ids', array());
        if ($ids == 0) {
            return $this->result->fail(ERROR_INVALID_DATA, Yii::t('Cms.ContentContext','Invalid ID.'));
        }
      
        if (!is_array($ids)) $ids = array($ids);
        foreach($ids as $id) {
            $model = ContentContext::model()->findByPk($id);
            /**
            * TODO: Check related data if this ContentContext is deletable
            * This can be done in onBeforeDelete or here or in extensions
            *
            if (Related::model()->count("ContentContextId = {$id}") > 0)
                $this->result->fail(ERROR_VIOLATING_BUSINESS_RULES, Yii::t('Cms.ContentContext',"Cannot delete ContentContext ID={$id} as it has related class data."));
            else
            */
                try {
                    $model->delete();
                } catch (CDbException $ex) {
                    $this->result->fail(ERROR_HANDLING_DB, $ex->getMessage());
                }
        }
        return $this->result;
    }
}